/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.uoc.tdp.pac4.servidor;


//import edu.uoc.tdp.pac4.beans.Proveidor;
import edu.uoc.tdp.pac4.beans.Perfil;
import edu.uoc.tdp.pac4.beans.Usuari;
import edu.uoc.tdp.pac4.comun.GestorLoginInterface;
import edu.uoc.tdp.pac4.i18n.TDSLanguageUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


/**
 *
 * @author andres
 */
public class GestorLoginImpl extends UnicastRemoteObject implements GestorLoginInterface, Serializable{

    private static final long serialVersionUID = 1L;
    public Connection conexion;
     final String propertiesFile = new File("").getAbsolutePath() + "//src//properties///configuration.properties";
    /* Linux Config */
    //final String propertiesFile = new File("").getAbsolutePath() + "/src/properties/configuration.properties";
    final String driver = "org.postgresql.Driver";
    
    
    public GestorLoginImpl() throws RemoteException, ExceptionBD {
        conectaBD();
    }

    public GestorLoginImpl(int paramInt) throws RemoteException, ExceptionBD {
        super(paramInt);
        conectaBD();
    }

    
    private void conectaBD() throws ExceptionBD {
        try {
            Class.forName("org.postgresql.Driver");
            Properties localProperties = new Properties();
            localProperties.load(new FileInputStream(this.propertiesFile));
            String str1 = localProperties.getProperty("url");
            String str2 = localProperties.getProperty("username");
            String str3 = localProperties.getProperty("password");
            
            
            this.conexion = DriverManager.getConnection(str1, str2, str3);
        } catch (ClassNotFoundException localClassNotFoundException) {
            Servidor.diplay(localClassNotFoundException.getMessage());
            throw new ExceptionBD(TDSLanguageUtils.getMessage("Aplication.JDBCKO"));
            
        } catch (FileNotFoundException localFileNotFoundException) {
            Servidor.diplay(localFileNotFoundException.getMessage());
            throw new ExceptionBD(TDSLanguageUtils.getMessage("Aplication.ConfigurationKO"));
        } catch (IOException localIOException) {
            Servidor.diplay(localIOException.getMessage());
            throw new ExceptionBD(TDSLanguageUtils.getMessage("Aplication.PropertiesKO"));
        } catch (SQLException localSQLException) {
            Servidor.diplay(localSQLException.getMessage());
            throw new ExceptionBD(TDSLanguageUtils.getMessage("Aplication.BBDDKO"));
        } catch (Exception localException) {
            Servidor.diplay(localException.getMessage());
            throw new ExceptionBD(localException.getMessage());
        }
    }
    
    
    
    
    @Override
    public int usuariLogin(String username, String password) throws RemoteException, SQLException {
        int id = 0;
        Statement st = null;
        ResultSet result = null;
        try {
            st = this.conexion.createStatement(1004, 1008);
            String str = "SELECT \"Usuari\".\"ID\" FROM \"public\".\"Usuari\" WHERE \"usuari\" = '"+username+"' AND \"contrasenya\" = '"+password+"' AND \"actiu\" = TRUE LIMIT 1";
            result = st.executeQuery(str);
            Servidor.diplay("ConsultaBD: " + str);
            
            System.out.println(str);
            
           /* Comprovació del nombre de files
            Si = 0 -> No s'ha trobat
            Si = 1 -> OK 
            */ 
            int rowCount = result.last() ? result.getRow() : 0;
            result.beforeFirst();
            
            System.out.println("Resultado : "+rowCount);
            
            if(rowCount==1) {
                while(result.next()) {
                    id = result.getInt("ID");
                }
            } 
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return id ;
    }
    
    public String saludo() {
        return "Hola campeon!";
    }
    
    public Usuari loadUsuari(int id) throws RemoteException, SQLException {
        Usuari u = new Usuari();
        u.setID(0);
        Statement st = null;
        ResultSet result = null;
        
        try {
            st = this.conexion.createStatement();
            String str = "SELECT * FROM \"public\".\"Usuari\" WHERE \"ID\" = '"+id+"' AND  \"actiu\" = TRUE LIMIT 1";
            result = st.executeQuery(str);
            Servidor.diplay("ConsultaBD: " + str);
            System.out.println(str);
            
            while(result.next()) {
                System.out.println("ID "+result.getInt("ID")+" Username "+result.getString("usuari"));
                u.setID(result.getInt("ID"));
                u.setUsuari(result.getString("usuari"));
                u.setPerfil(this.loadPerfil(result.getInt("perfil")));
                u.setContrasenya(result.getString("contrasenya"));
                u.setActiu(result.getBoolean("actiu"));
                u.setDataAlta(result.getDate("dataAlta"));
                u.setDataModificacio(result.getDate("dataModificacio"));
                u.setDataBaixa(result.getDate("dataBaixa"));
                u.setReparacionsAssignades(result.getInt("reparacionsassignades")); 
                
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }
    
   private Perfil loadPerfil(int id) throws RemoteException, SQLException {
            Statement st = null;
            ResultSet result = null;
            Perfil p =  new Perfil();
            
        try {
            st = this.conexion.createStatement();
            String str = "SELECT * FROM \"public\".\"Perfil\" WHERE \"ID\" = "+id;
            result = st.executeQuery(str);
            //Servidor.diplay("ConsultaBD: " + str);
            System.out.println(str);
            
            while(result.next()) {
                
                p.setId(result.getInt("ID"));
                p.setPerfil(result.getString("perfil"));
                p.setDataAlta(result.getDate("dataAlta"));
                p.setDataModificacio(result.getDate("dataModificacio"));
                p.setDataBaixa(result.getDate("dataBaixa"));
                
            }
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
            return p;
    }
    
    
}
